// 一. 导入express包
const express = require("express")
//导入数据库配置文件
const { debug } = require("../config")
const { getAll, getById, exec } = require("../db")
// 二. 创建router路由对象
const router = express.Router()
// 三. 编写路由规则

/**
 * 获取所有公告
 * GET /ggnotice
 */

router.get("/", async (req, res) => {
  //解析请求参数
  const { page = 2, size = 5 } = req.query
  //操作数据库
  //查询gg_notice表中的记录总和并取名total
  let sql = `select count(*) as total from gg_notice`
  let { total } = await getById(sql)

  /* 获取全部 */
  sql = `select * from gg_notice`
  const dataA = await getAll(sql)
  //计算偏移量
  let offset = (page - 1) * size
  // 操作数据库
  sql = `select * from gg_notice ORDER BY notice_id desc limit ${offset}, ${size}`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: "获取公告成功",
    result: { data, dataA, total },
  })
})

/**
 * 根据id获取单个用户数据
 * GET /ggnotice/:id
 */
router.get("/:id", async (req, res) => {
  const { id } = req.params

  try {
    //操作数据库
    let sql = `select * from gg_notice where notice_id=${id}`
    const data = await getById(sql)

    if (data) {
      res.send({
        code: 0,
        msg: "获取单个用户成功",
        result: data,
      })
    } else {
      res.send({
        code: 100102,
        msg: "id对应的数据不存在",
        result: "",
      })
    }
  } catch (error) {
    res.send({
      code: 100103,
      msg: "获取单个代办失败",
      result: debug ? error : "",
    })
  }
})

/**
 * 新增公告
 * POST /ggnotice
 */
router.post("/", async (req, res) => {
  // 一. 解析请求参数
  const { user_id, notice_content, notice_time } = req.body
  // 二. 操作数据库
  let sql = `insert into gg_notice (user_id,notice_content, notice_time ) 
  values (${user_id}, '${notice_content}' , NOW())`
  const data = await exec(sql)
  // 三. 返回结果
  try {
    res.send({
      code: 0,
      message: "新增公告成功",
      result: {
        id: data.insertId,
        user_id,
        notice_content,
        notice_time,
      },
    })
  } catch (err) {
    res.send({
      code: 100101,
      message: "修改公告失败",
      result: debug ? err : "",
    })
  }
})

/**
 * 删除公告
 * DELETE /gg_user/:id
 */
router.delete("/:id", async (req, res) => {
  // 一. 解析请求参数
  const { id } = req.params
  // 二. 操作数据库
  let sql = `delete from gg_notice where notice_id=${id}`
  await exec(sql)
  // 三. 返回结果
  res.send({
    code: 0,
    message: "删除公告成功",
    result: "",
  })
})

// 四. 导出路由对象
module.exports = router
